import 'package:hive/hive.dart';
import 'package:path/path.dart' as p;
import '../../env/environment_service.dart';
import '../../model/play/video_detail_model.dart';
import '../consts.dart';
import '../enum.dart';
import '../utils.dart';
import 'm3u8_download_record_state.dart';

part 'm3u8_download_record.g.dart';

@HiveType(typeId: Consts.hiveTypeIdDownloadRecord)
class M3u8DownloadRecord {
  @HiveField(0)
  final DateTime createdAt;
  @HiveField(1)
  final int videoId;
  @HiveField(2)
  int? playTime;
  @HiveField(3)
  final String videoUrl;
  @HiveField(4)
  final String authKey;
  @HiveField(5)
  final String cover;
  @HiveField(6)
  final String? title;
  @HiveField(7)
  final VideoTypeEnum videoType;
  @HiveField(8)
  final double? price;
  @HiveField(9)
  final String? _filenameWithoutExtension;
  @HiveField(10)
  M3u8DownloadRecordState state;
  @HiveField(11)
  String? stateDesc;
  @HiveField(12)
  final String id;
  @HiveField(13)
  String downloadFilepath;

  M3u8DownloadRecord({
    required this.videoId,
    this.playTime,
    required this.videoUrl,
    required this.authKey,
    required this.cover,
    this.title,
    required this.videoType,
    this.price,
    required this.state,
    this.stateDesc,
    required this.id,
    required this.downloadFilepath,
    String? filenameWithoutExtension,
  })  : createdAt = DateTime.now(),
        _filenameWithoutExtension = filenameWithoutExtension;

  bool get isWaiting => M3u8DownloadRecordStateEnum.isWaiting(state);
  bool get isSuccess => M3u8DownloadRecordStateEnum.isSuccess(state);
  bool get isError => M3u8DownloadRecordStateEnum.isError(state);
  bool get isCancel => M3u8DownloadRecordStateEnum.isCancel(state);
  bool get isFininshed => M3u8DownloadRecordStateEnum.isFinished(state);

  String get filenameWithoutExtension {
    if (_filenameWithoutExtension != null) return _filenameWithoutExtension;
    if (title?.isNotEmpty == true) {
      final basename = p.basenameWithoutExtension(title!);
      const nameLenMax = 150;
      if (basename.length > nameLenMax) {
        return basename.substring(0, nameLenMax);
      }
      return basename;
    }
    return Utils.md5String(videoUrl);
  }

  Uri? get fullUrl =>
      Uri.parse("${Environment.kbaseAPI}m3u8/decode/by/id?videoId=$videoId");

  M3u8DownloadRecord.videoDetail(VideoDetail detail,
      {String? filenameWithoutExtension})
      : createdAt = DateTime.now(),
        videoId = detail.videoId!,
        playTime = detail.playTime,
        videoUrl = detail.videoUrl!,
        authKey = '',
        cover = detail.hCover,
        title = detail.title,
        videoType = detail.videoType!,
        price = detail.price,
        _filenameWithoutExtension = filenameWithoutExtension,
        id = '',
        state = M3u8DownloadRecordStateEnum.waiting,
        downloadFilepath = '';
}
